package cn.com.ahao.gateway.route;

import cn.com.ahao.gateway.service.IApiCodeService;
import cn.com.ahao.gateway.vo.dvo.ApiCodeDVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.PredicateSpec;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.function.Function;

@Configuration
public class RouteConfig {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Bean
//    public RouteLocator customizeRoute(RouteLocatorBuilder builder) {
//        RouteLocatorBuilder.Builder routes = builder.routes();
//        routes.route("nacos-service",
//                r -> r.path("/api/nacos/**")
//                        .filters(filter -> filter.stripPrefix(2))
//                        .uri("lb://nacos-demo"));
//        return routes.build();
//    }

    @Autowired
    private IApiCodeService apiCodeService;

    @Bean
    public RouteLocator customizeRoute(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        // 1.固定路由
        routes.route(r -> r.path("/api/nacos/firstApi/sayHello").filters(filter -> filter.stripPrefix(2)).uri("lb://nacos-demo"));

        // 2.路由映射
        List<ApiCodeDVO> list = apiCodeService.list();
        for (ApiCodeDVO dvo : list) {
            logger.info("dvo: {}, ", dvo.toString());
            Function<PredicateSpec, Route.AsyncBuilder> predicateSpecAsyncBuilderFunction =
                    r -> r.path("/api/" + dvo.getApiCode())
                            // rewirtePath的功能是把/api/MS00001访问路径修改为/hello
                            .filters(filter -> filter.rewritePath("/api/" + dvo.getApiCode(), dvo.getUrl()))
                            .uri("lb://" + dvo.getSystemCode());
            routes.route(predicateSpecAsyncBuilderFunction);
        }
        return routes.build();
    }
}
